/**
**********************************************************************************************************************************************************************************************************************************
* @file:	FilePermissions.h
* @author:	zinface
* @date:	2021年09月22日 18:56:12 星期三
* @brief:	FinalC 提供的 FilePermissions 文件权限信息操作
**********************************************************************************************************************************************************************************************************************************
**/

// #ifndef __FILEPERMISSIONS__H__
// #define __FILEPERMISSIONS__H__

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>

#include "FinalCType/FilePermissions.h"

// FinalC_Object_Define(FilePermissions) {
//     bool isRead;
//     bool isWrite;
//     bool isExecute;
//     struct stat st;
//     String str;
// };
FinalC_Object_Size(FilePermissions);

// #define FinalC_FilePermission_Func_Define(func) \
//         FinalC_Object_Func_Suffix(filePermission, func)

// ------------------------------------ Constructor
FINALC_WARN_UNUSED_RESULT
FinalC_Object_Create_Define(FilePermissions) {
    FilePermissions *perm = (FilePermissions*)calloc(FilePermissionsSize(), 1);
    
    perm->isRead = false;
    perm->isWrite = false;
    perm->isExecute = false;

    clearString(&perm->str);

    return perm;
}

void FinalC_FilePermission_Func_Define(Set)(FilePermissions *perm, bool isread, bool iswrite, bool isexec) {
    perm->isRead = isread;
    perm->isWrite = iswrite;
    perm->isExecute = isexec;
}

void filePermissionSetWith_stat(FilePermissions *perm, struct stat st) {
    filePermissionSet(perm,
        ((S_IRUSR & st.st_mode) != 0), 
        ((S_IWUSR & st.st_mode) != 0), 
        ((S_IXUSR & st.st_mode) != 0));
}

void filePermissionSetWith_cstr(FilePermissions *perm, char *str) {
    stat(str, &perm->st);

    filePermissionSetWith_stat(perm, perm->st);
    
    clearString(&perm->str);
    
    char buffer[100] = {0};
    sprintf(buffer, "%s%s%s",  
                    perm->isRead?"r":"-",
                    perm->isWrite?"w":"-",
                    perm->isExecute?"x":"-");
    stringAppend_cstr(&perm->str, buffer);
}


FilePermissions *createFilePermissionWith_cstr(char *str) {
    FilePermissions *perm = createFilePermissions();
    
    lstat(str, &perm->st);

    filePermissionSetWith_stat(perm, perm->st);

    return perm;
}

// ------------------------------------ Destructor
FinalC_Object_Destroy_Define(FilePermissions) {
    if (v) v->isRead = false;
    if (v) v->isWrite = false;
    if (v) v->isExecute = false;
    if (v) clearString(&v->str);
    if (v) v = NULL;
}

FinalC_Object_Delete_Define(FilePermissions) {
    if (v) clearString(&v->str);
    if (v) free(v);
    if (v) v = NULL;
}

// #endif  //!__FILEPERMISSIONS__H__